package com.caesar.gxmz;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;

public class FragmentPage1 extends Fragment {
	private static String titleString = null;
	private static String summaryString = null;
	private static String imageString = null;
	private ProgressDialog progressDialog = null;
	private String startString = null;
	private boolean timelineFlag = false;
	private WebView webView;
	private SwipeRefreshLayout swipeLayout;
	private LinearLayout rl_titile_bar_right, rl_titile_bar_right2;
	private ImageView btnBack, img_look_up2, img_look_up3;
	private static final String LOG_TAG = "ImageDownloader";
	private int imageNumber = 0;
	private int fileCount = 0;
	private FinalHttp fh;
	private String kDescription = "易美居";
	private String house_id = null;
	private List<File> files;
	private static String urlString = "http://web.fdcanet.com/index.php?app=agent&id=7907924";
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progressDialog.show();
				GetShareTask shareTask = new GetShareTask();
				shareTask.execute();
				break;
			case 2:
				progressDialog.show();
				GetShareImageTask shareTask1 = new GetShareImageTask();
				shareTask1.execute();
				break;
			case 3:
				ProcessShareImageTask shareTask2 = new ProcessShareImageTask();
				shareTask2.execute();
				break;
			case 4:
				GetShareTextTask shareTask3 = new GetShareTextTask();
				shareTask3.execute();
				break;
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_1, null);

	}

	@SuppressLint("SetJavaScriptEnabled")
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (hasSdcard()) {
			String pathName = Environment.getExternalStorageDirectory()
					+ File.separator + LOG_TAG;
			File file = new File(pathName);
			if (!file.isDirectory()) {
				file.mkdir();
			}
		} else {
			Toast.makeText(getActivity(), "您的手机可能缺少储存卡", Toast.LENGTH_SHORT)
					.show();
		}
		webView = (WebView) getActivity().findViewById(R.id.myWebView_01);
		progressDialog = new ProgressDialog(getActivity());
		progressDialog.setMessage("请耐心等待...");
		SharedPreferences sp = getActivity().getSharedPreferences("MarrayNote",
				Activity.MODE_PRIVATE);
		String user_role = sp.getString("user_role", "agent");
		String sid = sp.getString("sid", "b88cd68e0fd00e7b3b6ef5210df83d99");
		WebSettings wSet = webView.getSettings();
		wSet.setJavaScriptEnabled(true);
		wSet.setJavaScriptCanOpenWindowsAutomatically(true);
		wSet.setAllowFileAccess(true);// 设置允许访问文件数据
		wSet.setSupportZoom(false);
		wSet.setBuiltInZoomControls(false);
		wSet.setJavaScriptCanOpenWindowsAutomatically(true);
		wSet.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		wSet.setDomStorageEnabled(true);
		wSet.setDatabaseEnabled(true);
		startString = sp.getString("redirect_url", urlString);
		if (user_role.equals("user"))
			startString = "http://web.fdcanet.com/index.php?app=user_home&appid=1&mobile=1&sid="
					+ sid;
		urlString = startString;
		Log.d("urlString", urlString);
		wSet.setCacheMode(WebSettings.LOAD_DEFAULT);
		btnBack = (ImageView) getActivity().findViewById(R.id.btnBack1);
		img_look_up2 = (ImageView) getActivity()
				.findViewById(R.id.img_look_up2);
		img_look_up3 = (ImageView) getActivity()
				.findViewById(R.id.img_look_up3);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (webView.canGoBack()) {
					webView.goBack();
				}
			}
		});
		webView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
				if (url.contains("house_search")) {
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
					handler.sendEmptyMessage(1);
					rl_titile_bar_right2.setVisibility(View.INVISIBLE);
				} else if (url.contains("about_us")) {
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
					handler.sendEmptyMessage(1);
					rl_titile_bar_right2.setVisibility(View.INVISIBLE);
				} else if (url.contains("house_detail")) {
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
					handler.sendEmptyMessage(1);
					rl_titile_bar_right2.setVisibility(View.VISIBLE);
				} else if (url.contains("article")) {
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
					handler.sendEmptyMessage(1);
					rl_titile_bar_right2.setVisibility(View.INVISIBLE);
				} else if (url.contains("share_favorite")) {
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
					handler.sendEmptyMessage(1);
				} else if (url.contains("act=logout")) {
					return false;
				} else if (url.equals(startString)) {
					btnBack.setVisibility(View.INVISIBLE);
					rl_titile_bar_right2.setVisibility(View.INVISIBLE);
					urlString = url;
				} else {
					btnBack.setVisibility(View.VISIBLE);
					rl_titile_bar_right2.setVisibility(View.INVISIBLE);
					urlString = url;
				}
				view.loadUrl(url);
				return true;
			}
		});

		rl_titile_bar_right = (LinearLayout) getActivity().findViewById(
				R.id.rl_titile_bar_right1);
		rl_titile_bar_right2 = (LinearLayout) getActivity().findViewById(
				R.id.rl_titile_bar_right2);
		rl_titile_bar_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showShare(getActivity(), null, false);
			}
		});
		img_look_up2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				final String items[] = { "分享图片", "分享文字" };
				AlertDialog dialog = new AlertDialog.Builder(getActivity())
						.setTitle("列表对话框")
						// 设置对话框的标题
						.setItems(items, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								if (which == 0) {
									handler.sendEmptyMessage(2);
									timelineFlag = false;
								} else {
									handler.sendEmptyMessage(4);
								}
							}
						})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).create();
				dialog.show();
			}
		});
		img_look_up3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				handler.sendEmptyMessage(2);
				timelineFlag = true;
			}
		});

		// 解决输入框不能输入的bug
		// webView.setOnTouchListener(new WebView.OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// if (flag) {
		// switch (event.getAction()) {
		// case MotionEvent.ACTION_DOWN:
		// case MotionEvent.ACTION_UP:
		// v.requestFocusFromTouch();
		// break;
		// case MotionEvent.ACTION_MOVE:
		// break;
		// case MotionEvent.ACTION_CANCEL:
		// break;
		// }
		// }
		// return false;
		// }
		// });
		CookieSyncManager.createInstance(getActivity());
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		cookieManager.removeSessionCookie();// 移除
		Cookie sessionCookie = Utils.appCookie;
		if (sessionCookie != null) {
			String cookieString = sessionCookie.getName() + "="
					+ sessionCookie.getValue() + "; domain="
					+ sessionCookie.getDomain();
			cookieManager.setCookie(urlString, cookieString);
			CookieSyncManager.getInstance().sync();
		}
		webView.loadUrl(urlString);
		swipeLayout = (SwipeRefreshLayout) getActivity().findViewById(
				R.id.swipe_container);
		swipeLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

					@Override
					public void onRefresh() {
						// 重新刷新页面
						webView.loadUrl(urlString);
					}
				});
		files = new ArrayList<File>();
	}

	public boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return true;
		}
	}

	/**
	 * 演示调用ShareSDK执行分享
	 * 
	 * @param context
	 * @param platformToShare
	 *            指定直接分享平台名称（一旦设置了平台名称，则九宫格将不会显示）
	 * @param showContentEdit
	 *            是否显示编辑页
	 */
	public static void showShare(Context context, String platformToShare,
			boolean showContentEdit) {
		OnekeyShare oks = new OnekeyShare();
		oks.setSilent(!showContentEdit);
		if (platformToShare != null) {
			oks.setPlatform(platformToShare);
		}
		// ShareSDK快捷分享提供两个界面第一个是九宫格 CLASSIC 第二个是SKYBLUE
		oks.setTheme(OnekeyShareTheme.CLASSIC);
		// 令编辑页面显示为Dialog模式
		oks.setDialogMode();
		// 在自动授权时可以禁用SSO方式
		oks.disableSSOWhenAuthorize();
		// oks.setAddress("12345678901"); //分享短信的号码和邮件的地址
		if (titleString == null) {
			titleString = "易美居";
		}
		if (summaryString == null) {
			summaryString = "中国人在美国都买什么样的房子";
		}
		if (imageString == null) {
			imageString = "http://web.fdcanet.com/data/files/mall/article/37/18439.jpg";
		}
		oks.setTitle(titleString);
		oks.setTitleUrl(urlString);
		oks.setText(summaryString + " " + urlString);
		// oks.setImagePath("/sdcard/test-pic.jpg"); //分享sdcard目录下的图片
		oks.setImageUrl(imageString);
		oks.setUrl(urlString); // 微信不绕过审核分享链接
		// oks.setFilePath("/sdcard/test-pic.jpg");
		// //filePath是待分享应用程序的本地路劲，仅在微信（易信）好友和Dropbox中使用，否则可以不提供
		oks.setComment(summaryString); // 我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
		oks.setSite(titleString); // QZone分享完之后返回应用时提示框上显示的名称
		oks.setSiteUrl(urlString);// QZone分享参数
		oks.setVenueName(titleString);
		oks.setVenueDescription(imageString);
		// 将快捷分享的操作结果将通过OneKeyShareCallback回调
		// oks.setCallback(new OneKeyShareCallback());
		// 去自定义不同平台的字段内容
		// oks.setShareContentCustomizeCallback(new
		// ShareContentCustomizeDemo());
		// 在九宫格设置自定义的图标
		Bitmap logo = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ic_launcher);
		String label = "易美居";
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {

			}
		};
		oks.setCustomerLogo(logo, label, listener);

		// 为EditPage设置一个背景的View
		// oks.setEditPageBackground(getPage());
		// 隐藏九宫格中的新浪微博
		// oks.addHiddenPlatform(SinaWeibo.NAME);

		// String[] AVATARS = {
		// "http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
		// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
		// "http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
		// "http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
		// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
		// "http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg"
		// };
		// oks.setImageArray(AVATARS); //腾讯微博和twitter用此方法分享多张图片，其他平台不可以

		// 启动分享
		oks.show(context);
	}

	public void exit() {
		removeCookie();
		getActivity().finish();
		Intent startMain = new Intent(Intent.ACTION_MAIN);
		startMain.addCategory(Intent.CATEGORY_HOME);
		startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(startMain);
		System.exit(0);
	}

	private void removeCookie() {
		CookieSyncManager.createInstance(getActivity());
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}

	class GetShareTask extends AsyncTask<String, String, String> {
		private String jsonString = null;

		protected String doInBackground(String... param) {
			HttpGet request = new HttpGet(urlString + "&json=1");
			try {
				HttpResponse response = new DefaultHttpClient()
						.execute(request);
				if (response.getStatusLine().getStatusCode() != 404) {
					jsonString = EntityUtils.toString(response.getEntity());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return jsonString;
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			if (result != null) {
				try {
					JSONObject loginObject = new JSONObject(result);
					JSONObject dataObject = loginObject.getJSONObject("data");
					titleString = dataObject.getString("title");
					summaryString = dataObject.getString("summary");
					imageString = dataObject.getString("image");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	class GetShareImageTask extends AsyncTask<String, String, String> {
		private String jsonString = null;

		protected String doInBackground(String... param) {
			HttpGet request = new HttpGet(urlString + "&json=1");
			try {
				HttpResponse response = new DefaultHttpClient()
						.execute(request);
				if (response.getStatusLine().getStatusCode() != 404) {
					jsonString = EntityUtils.toString(response.getEntity());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return jsonString;
		}

		protected void onPostExecute(String result) {
			if (result != null) {
				files = new ArrayList<File>();
				String house[] = (urlString + "&json=1").split("&house_id=");
				String house_String = house[1];
				String houseID[] = house_String.split("&");
				house_id = houseID[0];
				try {
					JSONObject loginObject = new JSONObject(result);
					JSONObject dataObject = loginObject.getJSONObject("data");
					titleString = dataObject.getString("title");
					kDescription = dataObject.getString("summary");
					imageString = dataObject.getString("image");
					JSONObject imagesObj = dataObject.getJSONObject("images");
					imageNumber = 0;
					fileCount = 0;
					String savePath = null;
					if (hasSdcard()) {
						savePath = Environment.getExternalStorageDirectory()
								+ File.separator + LOG_TAG + File.separator
								+ "shareImage_" + house_id + "_" + imageNumber
								+ ".jpg";
					} else {
						savePath = Environment.getDownloadCacheDirectory()
								+ File.separator + "shareImage_" + house_id
								+ "_" + imageNumber + ".jpg";
					}
					File file = new File(savePath);
					if (imagesObj != null && imagesObj.length() > 0) {
						for (int i = 0; i < imagesObj.length(); i++) {
							files.add(file);
						}
						for (int i = 0; i < imagesObj.length(); i++) {
							String imageUrl = imagesObj.getString(String
									.valueOf(i + 1));
							saveImage(imageUrl, i);
						}
					}
				} catch (JSONException e) {
					progressDialog.dismiss();
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				progressDialog.dismiss();
			}

		}

	}

	class GetShareTextTask extends AsyncTask<String, String, String> {
		private String jsonString = null;

		protected String doInBackground(String... param) {
			HttpGet request = new HttpGet(urlString + "&json=1");
			try {
				HttpResponse response = new DefaultHttpClient()
						.execute(request);
				if (response.getStatusLine().getStatusCode() != 404) {
					jsonString = EntityUtils.toString(response.getEntity());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return jsonString;
		}

		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONObject loginObject = new JSONObject(result);
					JSONObject dataObject = loginObject.getJSONObject("data");
					titleString = dataObject.getString("title");
					kDescription = dataObject.getString("summary");
					imageString = dataObject.getString("image");
					Intent sendIntent = new Intent();
					sendIntent.setAction(Intent.ACTION_SEND);
					sendIntent.setType("text/plain");
					sendIntent.putExtra(Intent.EXTRA_TEXT, kDescription);
					sendIntent.putExtra(Intent.EXTRA_SUBJECT, kDescription);
					ComponentName comp = new ComponentName("com.tencent.mm",
							"com.tencent.mm.ui.tools.ShareImgUI");
					sendIntent.setComponent(comp);
					startActivity(sendIntent);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
			}

		}

	}

	private void saveImage(String imageUrl, final int position) {
		String savePath = null;
		if (hasSdcard()) {
			savePath = Environment.getExternalStorageDirectory()
					+ File.separator + LOG_TAG + File.separator + "shareImage_"
					+ house_id + "_" + imageNumber + ".jpg";
		} else {
			savePath = Environment.getDownloadCacheDirectory() + File.separator
					+ "shareImage_" + house_id + "_" + imageNumber + ".jpg";
		}
		File file = new File(savePath);
		if (file.exists()) {
			files.set(position, file);
			fileCount++;
			if (fileCount == files.size() - 1) {
				if (timelineFlag) {
					progressDialog.dismiss();
					Toast.makeText(getActivity(), "下载完成,准备分享...分享标题已复制，请长按复制粘贴...",
							Toast.LENGTH_SHORT).show();
					Intent sendIntent = new Intent();
					sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
					sendIntent.setType("image/*");
					sendIntent.putExtra("Kdescription", kDescription);
					sendIntent.putExtra(Intent.EXTRA_TEXT, kDescription);
					ComponentName comp = null;
					ArrayList<Uri> uris = new ArrayList<Uri>();
					for (File f : files) {
						Uri uri;
						 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//24
			                    uri = FileProvider.getUriForFile(getActivity(),"com.caesar.gxmz.fileprovider",f);
                             ContentResolver cR = getActivity().getContentResolver();
                             if (uri != null && uri.toString().length()>0) {
                                 String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
                                 if (fileType.length()>0){
                                     if (fileType.contains("video/")){
                                         uri = getVideoContentUri(getActivity(), f);
                                     }else if (fileType.contains("image/")){
                                         uri = getImageContentUri(getActivity(), f);
                                     }else if (fileType.contains("audio/")){
                                         uri = getAudioContentUri(getActivity(), f);
                                     }
                                 }
                             }
			                    Log.d("***uri***",uri.toString());
			                }else {
			                    uri = Uri.fromFile(f);
			                }
						 uris.add(uri);
					}
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
						ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
						ClipData mClipData = ClipData.newPlainText("Label", kDescription);
						cm.setPrimaryClip(mClipData);
					}
					sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,
							uris);
                    sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					comp = new ComponentName("com.tencent.mm",
							"com.tencent.mm.ui.tools.ShareToTimeLineUI");
					sendIntent.setComponent(comp);
					startActivity(sendIntent);
				} else {
					handler.sendEmptyMessage(3);
				}
			}
		} else {
			fh = new FinalHttp();
			fh.download(imageUrl, savePath, new AjaxCallBack<File>() {
				@Override
				public void onStart() {
					super.onStart();
					// Toast.makeText(getApplicationContext(), "开始下载" +
					// imageNumber,
					// Toast.LENGTH_SHORT).show();
				}

				@SuppressLint("DefaultLocale")
				@Override
				public void onLoading(long count, long current) {
					super.onLoading(count, current);
				}

				@Override
				public void onSuccess(File t) {
					super.onSuccess(t);
//                    try {
//                        MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), t.getPath(), "title", "description");
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
                    // Toast.makeText(getApplicationContext(), "下载完成" +
					// imageNumber,
					// Toast.LENGTH_SHORT).show();
					files.set(position, t);
					fileCount++;
					if (fileCount == files.size() - 1) {
						if (timelineFlag) {
							progressDialog.dismiss();
							Toast.makeText(getActivity(), "下载完成,准备分享...分享标题已复制，请长按复制粘贴...",
									Toast.LENGTH_SHORT).show();
							Intent sendIntent = new Intent();
							sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
							sendIntent.setType("image/*");
							sendIntent.putExtra("Kdescription", kDescription);
							sendIntent
									.putExtra(Intent.EXTRA_TEXT, kDescription);
							ArrayList<Uri> uris = new ArrayList<Uri>();
							for (File f : files) {
								Uri uri=null;
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//24
									uri = FileProvider.getUriForFile(getActivity(),"com.caesar.gxmz.fileprovider",f);
									ContentResolver cR = getActivity().getContentResolver();
									if (uri != null && uri.toString().length()>0) {
										String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
										if (fileType.length()>0){
											if (fileType.contains("video/")){
												uri = getVideoContentUri(getActivity(), f);
											}else if (fileType.contains("image/")){
												uri = getImageContentUri(getActivity(), f);
											}else if (fileType.contains("audio/")){
												uri = getAudioContentUri(getActivity(), f);
											}
										}
									}
									Log.d("***uri***",uri.toString());
								}else {
									uri = Uri.fromFile(f);
								}
								 uris.add(uri);
							}
							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
								ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
								ClipData mClipData = ClipData.newPlainText("Label", kDescription);
								cm.setPrimaryClip(mClipData);
							}
							sendIntent.putParcelableArrayListExtra(
									Intent.EXTRA_STREAM, uris);
							ComponentName comp = new ComponentName(
									"com.tencent.mm",
									"com.tencent.mm.ui.tools.ShareToTimeLineUI");
							sendIntent.setComponent(comp);
							sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);    //这一步很重要。给目标应用一个临时的授权。
							startActivity(sendIntent);
						} else {
							handler.sendEmptyMessage(3);
						}
					}
					// Intent intent = new
					// Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
					// Uri uri = Uri.fromFile(t);
					// intent.setData(uri);
					// ShareActivity.this.sendBroadcast(intent);
				}

				@Override
				public void onFailure(Throwable t, String strMsg) {
					// TODO Auto-generated method stub
					super.onFailure(t, strMsg);
					// Toast.makeText(getApplicationContext(), "下载失败" +
					// imageNumber,
					// Toast.LENGTH_SHORT).show();
				}

			});
		}
		imageNumber++;
	}

	class ProcessShareImageTask extends AsyncTask<String, String, String> {
		protected String doInBackground(String... param) {
			Bitmap canMap = null;
			if (files.size() < 4) {
				canMap = Bitmap.createBitmap(300, 300 * files.size(),
						Bitmap.Config.ARGB_8888);
				for (int i = 0; i < files.size(); i++) {
					Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
							.getAbsolutePath());
					Canvas canvas = new Canvas(canMap);
					canvas.drawBitmap(bitMap, i * 300, 0, null);
				}
			} else if (files.size() == 4) {
				canMap = Bitmap.createBitmap(600, 600, Bitmap.Config.ARGB_8888);
				for (int i = 0; i < files.size(); i++) {
					Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
							.getAbsolutePath());
					Canvas canvas = new Canvas(canMap);
					canvas.drawBitmap(bitMap, i % 2 * 300, i / 2 * 300, null);
				}
			} else if (files.size() > 4 && files.size() < 7) {
				canMap = Bitmap.createBitmap(600, 900, Bitmap.Config.ARGB_8888);
				for (int i = 0; i < files.size(); i++) {
					Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
							.getAbsolutePath());
					Canvas canvas = new Canvas(canMap);
					canvas.drawBitmap(bitMap, i % 3 * 300, i / 3 * 300, null);
				}
			} else if (files.size() >= 7) {
				canMap = Bitmap.createBitmap(900, 900, Bitmap.Config.ARGB_8888);
				for (int i = 0; i < files.size(); i++) {
					Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
							.getAbsolutePath());
					Canvas canvas = new Canvas(canMap);
					canvas.drawBitmap(bitMap, i % 3 * 300, i / 3 * 300, null);
				}
			}
			String newPathString = Environment.getExternalStorageDirectory()
					+ File.separator + LOG_TAG + File.separator + "shareImage_"
					+ house_id + "_" + (imageNumber + 1) + ".jpg";
			File file = new File(newPathString);// 将要保存图片的路径
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(file));
				canMap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return newPathString;
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			if (result != null) {
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
				sendIntent.setType("image/*");
				sendIntent.putExtra(Intent.EXTRA_TEXT, kDescription);
				ComponentName comp = new ComponentName("com.tencent.mm",
						"com.tencent.mm.ui.tools.ShareImgUI");
				File file = new File(result);// 将要保存图片的路径
				ArrayList<Uri> uris = new ArrayList<Uri>();
				Uri uri=null;
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//24
					uri = FileProvider.getUriForFile(getActivity(),"com.caesar.gxmz.fileprovider",file);
					ContentResolver cR = getActivity().getContentResolver();
					if (uri != null && uri.toString().length()>0) {
						String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
						if (fileType.length()>0){
							if (fileType.contains("video/")){
								uri = getVideoContentUri(getActivity(), file);
							}else if (fileType.contains("image/")){
								uri = getImageContentUri(getActivity(), file);
							}else if (fileType.contains("audio/")){
								uri = getAudioContentUri(getActivity(), file);
							}
						}
					}
					Log.d("***uri***",uri.toString());
				}else {
					uri = Uri.fromFile(file);
				}
				uris.add(uri);
				sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,
						uris);
				sendIntent.setComponent(comp);
//				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.addCategory("android.intent.category.DEFAULT");
//				sendIntent.putExtra(Intent.EXTRA_STREAM, uris);
				sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				startActivity(sendIntent);
			}
		}

	}

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param imageFile
     * @return content Uri
     */
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param videoFile
     * @return content Uri
     */
    public static Uri getVideoContentUri(Context context, File videoFile) {
        String filePath = videoFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Video.Media._ID }, MediaStore.Video.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/video/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (videoFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Video.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param audioFile
     * @return content Uri
     */
    public static Uri getAudioContentUri(Context context, File audioFile) {
        String filePath = audioFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Audio.Media._ID }, MediaStore.Audio.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/audio/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (audioFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
}
